// 最大上传图片数量
let MAX_IMG_NUM = 9
let openid = ''
const db = wx.cloud.database()
// 输入的文字内容
let content = ''
let headline = ''
let topic = '娱乐'
let userInfo = {}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 输入的文字个数
    // content: '',
    // wordsNum: 0,
    images: [],
    selectPhoto: true, // 添加图片元素是否显示
    array: [],
    index: 0,
    article: false,
    //富文本
    formats: {},
    readOnly: false,
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false
    //富文本
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._useriflogin()
    this._gettopicList()

    // 富文本
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)
    })
    // 富文本
  },
  // 富文本
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  // 富文本
  _useriflogin: function () {
    wx.cloud.callFunction({
      name: "login"
    }).then(res => {
      openid = res.result.userInfo.openId
      db.collection('user').where({
        _id: openid
      }).limit(1).get().then(res => {
        userInfo.avatarUrl = res.data[0].avatarUrl
        userInfo.nickName = res.data[0].nickName
      })
      
    }).catch(err => {
      console.log(err)
    })
  },
  // 富文本
  updatePosition(keyboardHeight) {
    this.setData({
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  // 富文本

  // 选择器
  pickerChange: function (e) {
    console.log(e)
    if (this.data.array[e.detail.value] == '文章') {
      this.setData({
        article: true
      })
    } else {
      this.setData({
        article: false
      })
    }
    this.setData({
      index: e.detail.value
    })
    if (e.detail.value == 4) {
      MAX_IMG_NUM = 1
    }
    topic = this.data.array[e.detail.value]
    // console.log(MAX_IMG_NUM)
  },

  // 标题和内容
  onInputtext(event) {
    headline = event.detail.value
  },
  onInput(event) {
    // console.log(event.detail.html)
    content = event.detail.html
  },

  onChooseImage() {
    // 还能再选几张图片
    let max = MAX_IMG_NUM - this.data.images.length
    wx.chooseImage({
      count: max,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // console.log(res)
        this.setData({
          images: this.data.images.concat(res.tempFilePaths)
        })
        // 还能再选几张图片
        max = MAX_IMG_NUM - this.data.images.length
        this.setData({
          selectPhoto: max <= 0 ? false : true
        })
      },
    })
  },
  onDelImage(event) {
    this.data.images.splice(event.target.dataset.index, 1)
    this.setData({
      images: this.data.images
    })
    if (this.data.images.length == MAX_IMG_NUM - 1) {
      this.setData({
        selectPhoto: true,
      })
    }
  },

  onPreviewImage(event) {
    // 6/9
    wx.previewImage({
      urls: this.data.images,
      current: event.target.dataset.imgsrc,
    })
  },
  send: function () {
    // 2、数据 -> 云数据库
    // 数据库：内容、图片fileID、openid、昵称、头像、时间
    // 1、图片 -> 云存储 fileID 云文件ID
    if (topic == '文章') {
      if (headline.trim() === '' || content.trim() === '' || this.data.images.length <= 0) {
        wx.showToast({
          title: '请完善内容',
          icon: 'none',
          duration: 1500
        })
        return
      }
    } else {
      if (content.trim() === '' || this.data.images.length <= 0) {
        wx.showToast({
          title: '请完善内容',
          icon: 'none',
          duration: 1500
        })
        return
      }
    }

    wx.showLoading({
      title: '发布中',
      mask: true,
    })

    let promiseArr = []
    let fileIds = []
    // 图片上传
    for (let i = 0, len = this.data.images.length; i < len; i++) {
      let p = new Promise((resolve, reject) => {
        let item = this.data.images[i]
        // 文件扩展名
        let suffix = /\.\w+$/.exec(item)[0]
        wx.cloud.uploadFile({
          cloudPath: 'blog/' + Date.now() + '-' + Math.random() * 1000000 + suffix,
          filePath: item,
          success: (res) => {
            // console.log(res.fileID)
            fileIds = fileIds.concat(res.fileID)
            resolve()
          },
          fail: (err) => {
            console.error(err)
            reject()
          }
        })
      })
      promiseArr.push(p)
    }
    // 存入到云数据库
    if (topic == '文章') {
      Promise.all(promiseArr).then((res) => {
        db.collection('blog').add({
          data: {
            ...userInfo,
            topic,
            headline,
            content,
            img: fileIds,
            likeNum: 0, //点赞数量
            collectNum: 0, //收藏数量
            commentNum: 0, //评论数量
            state: true,
            createTime: db.serverDate(), // 服务端的时间
          }
        }).then((res) => {
          wx.hideLoading()
          wx.showToast({
            title: '发布成功',
          })
          wx.navigateTo({
            url: `../list/list?name=${topic}`,
          })
        })
      }).catch((err) => {
        wx.hideLoading()
        wx.showToast({
          title: '发布失败',
        })
      })
    } else {
      Promise.all(promiseArr).then((res) => {
        db.collection('blog').add({
          data: {
            ...userInfo,
            topic,
            content,
            img: fileIds,
            likeNum: 0, //点赞数量
            collectNum: 0, //收藏数量
            commentNum: 0, //评论数量
            state: true,
            createTime: db.serverDate(), // 服务端的时间
          }
        }).then((res) => {
          wx.hideLoading()
          wx.showToast({
            title: '发布成功',
          })
          wx.navigateTo({
            url: `../list/list?name=${topic}`,
          })
        })
      }).catch((err) => {
        wx.hideLoading()
        wx.showToast({
          title: '发布失败',
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  onTabItemTap(item) {
    //刷新页面
    this.setData({
      article: false,
      images: [],
      wordsNum: 0,
      index: 0,
      selectPhoto: true, // 添加图片元素是否显示
    })
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
      that.editorCtx.clear({
        success: function (res) {
          console.log("clear success")
        }
      })
    }).exec()

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //获取专题
  _gettopicList: function () {
    db.collection('topic').get().then((res) => {
      // console.log(res.data)
      let arr = []
      for (var i = 0; i < res.data.length; i++) {
        arr.push(res.data[i].name)
      }
      this.setData({
        array: arr
      })
    })
  },
})